package la.iok.hzsvn.lewin.movie.operation.controller;

import la.iok.hzsvn.lewin.movie.core.Token;
import la.iok.hzsvn.lewin.movie.operation.model.ConsumeDetail;
import la.iok.hzsvn.lewin.movie.operation.service.ConsumeDetailService;
import la.iok.hzsvn.share.excel.utils.ExcelUtils;
import la.iok.hzsvn.share.response.ListDataResponse;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;

import static org.springframework.http.HttpHeaders.CONTENT_DISPOSITION;
import static org.springframework.http.HttpHeaders.CONTENT_TYPE;

@RestController
@RequestMapping("consumeDetails")
public class ConsumeDetailController {
    private final ConsumeDetailService consumeDetailService;

    public ConsumeDetailController(ConsumeDetailService consumeDetailService) {
        this.consumeDetailService = consumeDetailService;
    }

    /**
     * 预览明细信息,用于处理旧数据,在更新之前可以看一下将要更新的数据
     * @return 消费明细预览数据
     */
    @GetMapping("preview")
    public ListDataResponse<ConsumeDetail> preview(@RequestHeader Token token, Long orgUnitId, Long roomId){
        return new ListDataResponse<>(consumeDetailService.preview(token,orgUnitId,roomId));
    }

    @PutMapping("ok")
    public ListDataResponse<ConsumeDetail> confirmUpdate(@RequestHeader Token token, Long orgUnitId, Long roomId){
        return new ListDataResponse<>(consumeDetailService.confirmUpdate(token,orgUnitId,roomId));
    }

    @GetMapping
    public ListDataResponse<ConsumeDetail> consumeDetail(@RequestHeader Token token, Long orgUnitId, Long roomId,String start, String end){
        return new ListDataResponse<>(consumeDetailService.exportData(token,orgUnitId,roomId,start,end));
    }

    @GetMapping("excel")
    public void excel(HttpServletResponse serverResponse, @RequestHeader Token token, Long orgUnitId, Long roomId,String start, String end) throws IOException {
        String file = "消费明细报表";
        serverResponse.setHeader(CONTENT_TYPE, MediaType.APPLICATION_OCTET_STREAM_VALUE);
        serverResponse.setHeader(CONTENT_DISPOSITION,"attachment;filename=" + URLEncoder.encode(file + ".xlsx","utf-8"));
        serverResponse.setHeader("Pragma", "no-cache");
        serverResponse.setHeader("Cache-Control", "no-cache");
        serverResponse.setDateHeader("Expires", 0);
        Workbook workbook = ExcelUtils.writeExcel(consumeDetailService.exportData(token,orgUnitId,roomId,start,end), ConsumeDetail.class,"消费明细",30f);
        workbook.write(serverResponse.getOutputStream());
        workbook.close();
    }
}
